package com.hyhy.hycloud.commons.util;

import java.util.*;

/**
 * @Package: com.hyhy.hycloud.commons.util
 * @Description: list按指定属性分组
 * @author:WUXIN
 * @date:2019/05/22 002217:26
 */
public class GroupUtil {
    public interface GroupBy<T> {
        T groupby(Object obj);
    }
    public static final <T extends Comparable<T>, D> Map<T, List<D>> group(Collection<D> colls, GroupBy<T> gb) {
        if (colls == null || colls.isEmpty()) {
            System.out.println("分组集合不能为空!");
            return null;
        }
        if (gb == null) {
            System.out.println("分组依据接口不能为Null!");
            return null;
        }
        Iterator<D> iter = colls.iterator();
        Map<T, List<D>> map = new LinkedHashMap<T, List<D>>();
        while (iter.hasNext()) {
            D d = iter.next();
            T t = gb.groupby(d);
            if (map.containsKey(t)) {
                map.get(t).add(d);
            } else {
                List<D> list = new ArrayList<D>();
                list.add(d);
                map.put(t, list);
            }
        }
        return map;
    }
}
